﻿using Zore.App.Shared.Extensions;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Zore.App.Shared.Helpers
{
    public static class StringHelper
    {
        public static string ToTitleCase(this string value)
        {
            if (value.IsNullOrWhiteSpace()) return null;

            return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value.ToLower());
        }

        public static bool IsNumeric(this string value)
        {
            if (value.IsNullOrWhiteSpace()) return false;

            return double.TryParse(value, out _);
        }

        public static string ToSlug(this string value)
        {
            if (value.IsNullOrWhiteSpace()) return null;

            return Regex.Replace(value.Trim(), @"[^a-zA-Z0-9\-]+", "-").ToLower();
        }

        public static string TryBase64(this string value)
        {
            // 去除任何可能的空白字符  
            var inputTrimmed = value.Trim();
            // 尝试解码  
            try
            {
                var data = System.Convert.FromBase64String(inputTrimmed);
                return System.Text.Encoding.UTF8.GetString(data);
            }
            catch
            {
                return value;
            }
        }
        public static Uri ToUri(this string input)
        {
            return new Uri(input);
        }

        /// <summary>
        /// 字符串截断并添加省略号
        /// </summary>
        public static string TruncateWithEllipsis(this string value, int maxLength)
        {
            if (value.IsNullOrWhiteSpace()) return null;

            if (value.Length <= maxLength)
            {
                return value;
            }
            else
            {
                return value.Substring(0, maxLength) + "...";
            }
        }

        public static string Reverse(this string value)
        {
            if (value.IsNullOrWhiteSpace()) return null;

            char[] chars = value.ToCharArray();
            Array.Reverse(chars);
            return new string(chars);
        }
    }
}
